package p.ithorns.framework.logger.stream;



import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;

/**
 * PipelineStream
 * <p>
 * 日志管道流
 *
 * @author 2021/10/23 16:41 by lht
 */
public class PipelineStream {

    private final static Logger log = LoggerFactory.getLogger(PipelineStream.class);

    private static final int BUFFER_SIZE = 1024 * 1024;

    private final Object lock = new Object();

    private PipedOutputStream out;

    private PipedInputStream in;


    public PipelineStream() {
        this.createPipe();
    }

    public void connect() {
        try {
            this.out.connect(this.in);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public OutputStream getOut() {
        // try {
        //     return new ObjectOutputStream(out);
        // } catch (IOException e) {
        //     throw new RuntimeException(e);
        // }
        return this.out;
    }

    public InputStream getIn() {
        // try {
        //     return new ObjectInputStream(in);
        // } catch (IOException e) {
        //     throw new RuntimeException(e);
        // }
        return this.in;
    }

    /**
     * 关闭
     */
    public void close() {
        try {
            if (null != out) {
                this.out.close();
            }
            if (null != in) {
                this.in.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public void createPipe() {
        synchronized (lock) {
            try {
                this.out = new PipedOutputStream();
                this.in = new PipedInputStream(out, BUFFER_SIZE);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}